package org.sakai.service;

import com.google.gson.Gson;
import org.sakai.entity.*;
import org.sakai.entity.vo.ConsultVO;
import org.sakai.mapper.ConsultMapper;
import org.sakai.mapper.DepartmentsMapper;
import org.sakai.mapper.DoctorMapper;
import org.sakai.mapper.PatientMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class ConsultService {
    @Autowired
    private DepartmentsMapper departmentsMapper;
    @Autowired
    private DoctorMapper doctorMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MinioService minioService;
    @Autowired
    private ConsultMapper consultMapper;
    @Autowired
    private PatientMapper patientMapper;
    public Result<List<Departments>> getDepartmentList()
    {
        Object o = redisTemplate.opsForValue().get("departmentList");
        if (o != null){
            return Result.success((List<Departments>) o);
        }
        List<Departments> departmentList = departmentsMapper.getDepartmentList();
        redisTemplate.opsForValue().set("departmentList", departmentList, 5, TimeUnit.MINUTES);
        return Result.success(departmentList);
    }

    public Result<Double> getPriceByDoctorId(String doctorId)
    {
        Double price = doctorMapper.getPriceByDoctorId(doctorId);
        if (price == null)return Result.error(ErrorCode.UNKNOWN_ERROR);
        return Result.success(price);
    }

    public Result<List<Doctor>> getDoctorListDetail(Long current, Long pageSize) {
        String cacheKey = "doctorListDetail:page:" + current + ":size:" + pageSize;
        List<Doctor> doctorList;
        // 从 Redis 获取缓存数据
        Object cachedData = redisTemplate.opsForValue().get(cacheKey);
        if (cachedData != null) {
            doctorList = (List<Doctor>) cachedData;
        } else {
            // 查询数据库并更新缓存
            doctorList = doctorMapper.getDoctorListDetail(current, pageSize);
            if (!doctorList.isEmpty()) {
                redisTemplate.opsForValue().set(cacheKey, doctorList, 5, TimeUnit.MINUTES);
                // 设置过期时间（例如 5 分钟）
                redisTemplate.expire(cacheKey, 5, TimeUnit.MINUTES);
            }
        }
        return Result.success(doctorList);
    }

    public Result<List<Doctor>> getDoctorListPreview(Long current, Long pageSize) {
        String cacheKey = "doctorListPreview:page:" + current + ":size:" + pageSize;
        List<Doctor> doctorList;
        // 从 Redis 获取缓存数据
        Object cachedData = redisTemplate.opsForValue().get(cacheKey);
        if (cachedData != null) {
            doctorList = (List<Doctor>) cachedData;
        } else {
            // 查询数据库并更新缓存
            doctorList = doctorMapper.getDoctorListPreview(current, pageSize);
            if (!doctorList.isEmpty()) {
                redisTemplate.opsForValue().set(cacheKey, doctorList, 5, TimeUnit.MINUTES);
                // 设置过期时间（例如 5 分钟）
                redisTemplate.expire(cacheKey, 5, TimeUnit.MINUTES);
            }
        }
        return Result.success(doctorList);
    }
    public Result<List<String>> uploadImages(List<String> base64Images, String consultId) {
        List<String> imageIds = new ArrayList<>();
        for (int i = 0; i < base64Images.size(); i++) {
            String imageId = UUID.randomUUID().toString();
            imageIds.add(imageId);
        }
        if (base64Images.size() != imageIds.size()) {
            return Result.error(ErrorCode.UNKNOWN_ERROR);
        }
        try {
            List<String> filenames = new ArrayList<>();
            List<UploadFileRequest> files = new ArrayList<>();
            for (int i = 0; i < base64Images.size(); i++) {
                String base64Image = base64Images.get(i);
                String imageId = imageIds.get(i);

                byte[] imageBytes = decodeBase64Image(base64Image);
                String fileName = imageId + "." + getBase64ImageType(base64Image); // 可根据实际类型调整扩展名
                filenames.add(fileName);
                files.add(new UploadFileRequest(fileName, imageBytes));
            }
            minioService.uploadFiles("big-data-health", consultId + "/images/", files);
            return Result.success(filenames);
        } catch (Exception e) {
            return Result.error(ErrorCode.UPLOAD_FILE_FAILED);
        }
    }
    public String getBase64ImageType(String base64Image) {
        if (!base64Image.startsWith("data:image/")) return null;

        String header = base64Image.split(",")[0]; // 例如 "data:image/png;base64"
        String contentType = header.split(";")[0];  // 提取 "data:image/png"
        return contentType.split("/")[1];           // 得到 "png" 或 "jpeg" 等
    }
    private byte[] decodeBase64Image(String base64Image) {
        if (base64Image.contains(",")) {
            base64Image = base64Image.split(",")[1]; // 去除 data:image/png;base64, 前缀
        }
        return Base64.getDecoder().decode(base64Image);
    }

    @Transactional
    public Result<String> addConsult(Consult consult) {
        final String CONTENT_KEY = "content";
        final String PENDING_PAYMENT = "待支付";

        // 校验并提取图片内容
        Object picturesObj = consult.getPictures();
        if (!(picturesObj instanceof List)) {
            return Result.error(ErrorCode.UNKNOWN_ERROR);
        }

        List<Map<String, Object>> pictures = (List<Map<String, Object>>) picturesObj;
        List<String> base64Images = new ArrayList<>();
        for (Map<String, Object> map : pictures) {
            Object contentObj = map.get(CONTENT_KEY);
            if (contentObj instanceof String) {
                String content = (String) contentObj;
                if (!content.isEmpty()) {
                    base64Images.add(content);
                }
            }
        }

        String id = UUID.randomUUID().toString();
        consult.setId(id);

        Result<List<String>> fileNamesResult = uploadImages(base64Images, id);

        String json = new Gson().toJson(fileNamesResult.getData());
        consult.setPictures(json);

        consult.setStatus(PENDING_PAYMENT);
        String doctorId = doctorMapper.selectRandomDoctorId();
        if (doctorId == null || doctorId.isEmpty()) {
            return Result.error(ErrorCode.UNKNOWN_ERROR);
        }
        consult.setDoctorId(doctorId);
        consult.setReConsultFlag((Integer)consult.getReConsultFlag() + 1);
        int insert = consultMapper.insertSelective(consult);
        if (insert <= 0) {
            return Result.error(ErrorCode.INSERT_ERROR);
        }

        return Result.success(id);
    }

    @Transactional
    public Result<String> updateConsultStatus(String consultOrderId, String status){
        Consult consult = new Consult();
        consult.setId(consultOrderId);
        consult.setStatus(status);
        int update = consultMapper.updateByPrimaryKeySelective(consult);
        if (update <= 0) {
            return Result.error(ErrorCode.UPDATE_ERROR);
        }
        return Result.success("更新成功");
    }

    public BigDecimal getPriceByOrderId(String id) {
        return consultMapper.selectByPrimaryKey(id).getPayment();
    }

    public Result<ConsultVO> getConsultDetail(String consultOrderId) {
        Consult consult = consultMapper.selectByPrimaryKey(consultOrderId);
        ConsultVO consultVO = new ConsultVO();
        BeanUtils.copyProperties(consult, consultVO);
        consultVO.setDocInfo(doctorMapper.selectByPrimaryKey(consult.getDoctorId()));
        consultVO.setPatientInfo(patientMapper.selectByPrimaryKey(consult.getPatientId()));
        return Result.success(consultVO);
    }
}
